﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using Metaspec;

//Solutions and independent projects can be parsed concurrently

namespace ParallelParsingExample
{
	class Program
	{
		static volatile int n_projects = 0;
		const int max_projects = 100;
		static ManualResetEvent eventX = new ManualResetEvent(false);

		static void Main(string[] args)
		{
			ThreadPool.SetMaxThreads(4,4);
			for (int i = 0; i != max_projects; ++i)
			{
				ThreadPool.QueueUserWorkItem(Thread_Start,i);
			}

			eventX.WaitOne(Timeout.Infinite, true);
		}

		static void Thread_Start(object objNumber)
		{
			int i = (int)objNumber;
			Console.WriteLine(string.Format("Thread {0} started", i));

			//creating project
			ICsProject project = ICsProjectFactory.create(project_namespace.pn_project_namespace);
			project.setBuildEntityModel(true);

			//adding assemblies
			string assembly_path = Assembly.GetAssembly(typeof(object)).Location;
			byte[] assembly_buffer = File.ReadAllBytes(assembly_path);
			IExternalAssemblyModule module = IExternalAssemblyModuleFactory.create(assembly_buffer, assembly_path);
			project.addExternalAssemblyModules(new IExternalAssemblyModule[] { module }, true, null);

			//adding C# file
			string directory = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"..\..");
			string path = Path.Combine(directory, "Project1.cs");
			char[] buffer = File.ReadAllText(path).ToCharArray();
			ICsFile file = ICsFileFactory.create(buffer, path);
			project.addFiles(file);

			//parsing
			project.parse(true, false);

			Console.WriteLine(string.Format("Thread {0} finished", i));

			Interlocked.Increment(ref n_projects);
			if (n_projects == max_projects)
			{
				eventX.Set();
			}
		}
	}
}
